<template>
  <div class="pageheader">
    <el-page-header @back="back">
      <template #content>
        <span> {{ info.project.name }} </span>
      </template>
    </el-page-header>
  </div>
  <div style="margin: 20px">
    <el-card>
      <div style="margin-bottom: 10px; display: flex">
        <el-input class="w-50 m-2" style="width: 150px" placeholder="请输入关键词" v-model="form.keywords" />
        <el-button style="margin-left: 10px" type="primary" @click="get">关键词搜索</el-button>
        <el-button @click="toAdd">新建方案</el-button>
        <el-button @click="doComparison">方案比选</el-button>
      </div>
      <el-table :data="state.tableData" :border="true" highlight-current-row class="dataTable"
        @selection-change="selectionChange">
        <el-table-column type="selection" />
        <el-table-column prop="id" label="ID" width="45" fixed="left" />
        <!--                <el-table-column prop="projectId" label="所属项目ID" width="100" />-->
        <el-table-column prop="name" label="方案标题" width="150" />
        <el-table-column prop="description" label="方案描述" />
        <el-table-column prop="equipType" label="装备类型" width="90" />
        <el-table-column prop="createTime" label="建立时间" width="150" />
        <el-table-column label="操作" width="350" fixed="right">
          <template v-slot="scope">
            <el-button link size="small" @click="toEdit(scope.row)">编辑</el-button>
            <el-button link type="primary" size="small" @click="toIndicator(scope.row)">方案设计</el-button>
            <el-button link type="primary" size="small" @click="doEva(scope.row)">评价</el-button>
            <el-button link type="primary" size="small" @click="toEva(scope.row)">查看评价</el-button>
            <el-popconfirm title="是否确认删除该项？" confirm-button-text="是" cancel-button-text="否"
                           @confirm="del(scope.row.id)">
              <template #reference>
                <el-button link type="danger" size="small">删除</el-button>
              </template>
            </el-popconfirm>

            <el-dropdown>
                  <span style="font-size: 12px; margin-top: 7px; margin-left: 12px">
                    更多操作
                  </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item>
                    <el-button link size="small" @click="copy(scope.row.id)">复制方案</el-button>
                  </el-dropdown-item>
                  <el-dropdown-item>
                    <el-button link size="small" @click="downloadTemplate(scope.row.id)">下载模板</el-button>
                  </el-dropdown-item>
                  <el-dropdown-item>
                    <el-button link size="small" @click="dlgImportState.visible = true; dlgImportState.form.id=scope.row.id">导入指标</el-button>
                  </el-dropdown-item>
                  <el-dropdown-item>
                    <el-button link size="small" @click="output(scope.row.id)">导出指标</el-button>
                  </el-dropdown-item>
                  <el-dropdown-item>
                    <el-button link size="small" @click="downloadReport(scope.row.id)">导出报告</el-button>
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>

          </template>
        </el-table-column>
      </el-table>
      <el-pagination class="pagination" v-model:current-page="form.current" v-model:page-size="form.size"
        :page-sizes="[10, 20, 50]" :small="false" :disabled="false" :background="true"
        layout="total, sizes, prev, pager, next, jumper" :total="state.total" @size-change="handleSizeChange"
        @current-change="handleCurrentChange" />
    </el-card>
  </div>
  <!-- 新增方案 -->
  <el-dialog v-model="dlgState.visible" :title="dlgState.title" :width="600" @close="clean">
    <el-form :model="dlgState.form" ref="dlg_form">
      <el-form-item label-width="100px" label="方案名称：" prop="name">
        <el-input v-model="dlgState.form.name"></el-input>
      </el-form-item>
      <el-form-item label-width="100px" label="方案描述：" prop="description">
        <el-input v-model="dlgState.form.description" type="textarea" :rows="3"></el-input>
      </el-form-item>
      <el-form-item label-width="100px" v-if="dlgState.isAdd" label="装备类型：" prop="description">
          <el-select style="width: 150px;" placeholder="请选择装备类型" v-model="dlgState.form.equipType">
            <el-option v-for="(item, index) in typeList" :key="index" :label="item.equipmentType"
                       :value="item.equipmentMark"></el-option>
          </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="cancelAdd">返回</el-button>
        <el-button type="primary" @click="doAdd" v-if="dlgState.isAdd">
          新增
        </el-button>
        <el-button type="primary" @click="doEdit" v-else> 保存 </el-button>
      </span>
    </template>
  </el-dialog>
  <!-- 导入指标 -->
  <el-dialog v-model="dlgImportState.visible" title="导入指标" :width="600" @close="clean">
    <el-form :model="dlgImportState.form" ref="dlg_form">
      <el-form-item  label="文件" prop="file" required>
        <el-upload action="#" :auto-upload="false" :multiple="false" :limit="1"
                   :on-change="changePic" :on-remove="removePic">
          <el-button type="primary">选择文件</el-button>
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dlgImportState.visible = false">返回</el-button>
        <el-button type="primary" @click="importIndicator">
          上传
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script lang="ts" setup>
import { ref, reactive, onMounted } from "vue";
import { ElMessage } from "element-plus";
import solutionApi from "@/api/equipment/solution";
import router from "@/router";
import generalSolution from "@/solutions/generalsolution";
import typeApi from "@/api/equipment/type";
import indicatorApi from "@/api/evaluation/indicator";
//import solution from "@/api/solution";

// type definition
type project = {
  id: number;
  name: string;
  type: number;
  createTime: Date;
  description: string;
};

// 初始化项目基本信息
const info = {
  project: { id: 0, name: "", type: 1, description: "", createTime: "" },
};
const proj = window.sessionStorage.getItem("project");
if (proj !== null) {
  info.project = JSON.parse(proj);
} else {
  ElMessage.error("未获取到项目信息！");
}
console.log(info.project);

// 列表数据
const form = reactive({
  current: 1,
  keywords: "",
  size: 10,
});
const state = reactive({
  total: 0,
  tableData: [],
});
const handleSizeChange = (val: number) => {
  form.size = val;
  get();
};
const handleCurrentChange = (val: number) => {
  form.current = val;
  get();
};
const get = () => {
  solutionApi.get(info.project.id, form).then((res) => {
    console.log(res);
    if (res.data.code === 200) {
      state.tableData = res.data.data.records;
      state.total = res.data.data.total;
    }
  });
};

// 新增方案（对话框）
const dlg_form = ref();
const dlgState = reactive({
  visible: false,
  isAdd: true,
  title: "新增方案",
  form: {
    id: 0,
    name: "",
    description: "",
    projectId: info.project.id,
    equipType: "1",
  },
});
const dlgImportState = reactive({
  visible: false,
  form : {
    id :0,
    file : null
  }
})

const importIndicator = () => {
  console.log(dlgImportState.form.file)
  indicatorApi.importIndicator(dlgImportState.form.id, {file : dlgImportState.form.file}).then((res) => {
    console.log(res)
    ElMessage.success("解析成功")
  })
}

const toAdd = () => {
  dlgState.isAdd = true;
  dlgState.title = "新增方案";
  dlgState.visible = true;
};
const cancelAdd = () => {
  dlgState.visible = false;
};
const doAdd = () => {
  solutionApi.add(dlgState.form).then((res) => {
    if (res.status === 200) {
      if (res.data.code === 500) {
        ElMessage.error("名称重复");
      } else {
        ElMessage.success("操作成功");
        dlgState.visible = false;
      }
      get();
    }
  });
};
const clean = () => {
  dlgState.form = {
    id: 0,
    name: "",
    description: "",
    projectId: info.project.id,
    equipType: "1"
  };
};

//编辑方案基本信息
const toEdit = (row: any) => {
  console.log(row);
  dlgState.form = row;
  dlgState.isAdd = false;
  dlgState.title = "编辑方案";
  dlgState.visible = true;
};

const downloadReport = (id:number) => {
  //   window.open(`http://localhost:8001/solution/report/${id}/3}`);
    ElMessage.error("该模块暂未开通此功能。")
  // }
};
const doEdit = () => {
  solutionApi.update(dlgState.form).then((res) => {
    console.log(res);
    if (res.status === 200) {
      if (res.data.code === 500) {
        ElMessage.error("名称重复");
      } else {
        ElMessage.success("操作成功");
        dlgState.visible = false;
      }
      get();
    }
  });
};
const downloadTemplate = (id:number) => {
  window.open(`http://localhost:8001/indicator/template/${id}`);
};
// 编辑方案指标信息
const toIndicator = (row: object) => {
  window.sessionStorage.setItem("solution", JSON.stringify(row));
  router.push("/equipment/solution/indicator");
};
// 删除方案
const del = (solId: number) => {
  solutionApi.del(solId).then((res) => {
    if (res.status === 200) {
      ElMessage.success("删除成功");
    }
    get();
  });
};

// 复制方案
const copy = (id: any) => {
  solutionApi.copy(id).then(() => {
    ElMessage.success("复制成功")
    get()
  })
}

// 多个方案比选
const multipleSelection = ref([] as Array<any>);
const selectionChange = (val: Array<any>) => {
  multipleSelection.value = val;
  console.log(multipleSelection.value);
};
const doComparison = () => {
  let form = [];
  for (const item of multipleSelection.value) {
    form.push(item);
  }
  console.log(form);
  if (form.length === 0) {
    ElMessage.warning("比选方案不能为空！");
    return;
  }
  window.sessionStorage.setItem("equipCompare", JSON.stringify(form))
  router.push("/equipment/compare")
  /* solutionApi.compare(form).then((res) => {
      console.log(res);
  }); */
};

// 评价
const toEva = (row: typeof generalSolution) => {
  window.sessionStorage.setItem("solution", JSON.stringify(row));
  router.push("/equipment/solution/eva");
};
const doEva = (row: any) => {
  console.log(row);
  solutionApi.eva(row.id).then((res) => {
    console.log(res);
    if (res.data.code === 200) {
      ElMessage.success("评价完成");
    }
  });
};

const changePic = (file: any) =>{
  dlgImportState.form.file = file.raw;
}
//删除文件
const removePic = () => {
  dlgImportState.form.file = null;
}
// 导出指标
const output = (id: any) => {
  console.log(id);
  window.open(`http://localhost:8001/indicator/output/${id}&ALL&3`);
};
// 回退
const back = () => {
  router.push("/equipment");
};
const typeList = ref([] as Array<any>)
const getTypes = () => {
  typeApi.getAll().then((res) => {
    typeList.value = res.data.data
  })
}
onMounted(() => {
  get();
  getTypes();
});
</script>
<style lang="scss" scoped>
.tabs>.el-tabs__content {
  width: 100%;
  padding: 32px;
  color: #6b778c;
  font-size: 32px;
  font-weight: 600;
}

.tabs {
  margin: 20px;
}
</style>
